<template>
    <div class="message-page">
        <!-- 添加联系人列表区域 -->
        <div class="contacts-panel">
            <div class="contacts-header">
                <h3>联系人</h3>
            </div>
            <div class="contacts-list">
                <div v-for="contact in contacts" :key="contact.id"
                    :class="['contact-item', { active: selectedContact?.id === contact.id }]"
                    @click="selectContact(contact)">
                    <el-avatar :size="36" :src="contact.avatar" />
                    <div class="contact-info">
                        <div class="contact-name">{{ contact.name }}</div>
                        <div class="contact-last-message">{{ contact.lastMessage }}</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 聊天窗口容器 -->
        <div class="chat-container">
            <div class="chat-messages" ref="messagesContainer">
                <div class="message-date">今天</div>

                <!-- 动态渲染消息列表 -->
                <div v-for="(message, index) in messages" :key="index" :class="['message-item', message.type]">
                    <!-- 系统消息 -->
                    <div v-if="message.type === 'system'" class="message-content">
                        {{ message.content }}
                    </div>

                    <!-- 接收消息 -->
                    <template v-else-if="message.type === 'received'">
                        <el-avatar :size="36"
                            :src="selectedContact?.avatar || 'https://cube.elemecdn.com/3/7c/3ea455e5a2e2d3d0f7a5a1c7c5d3b.jpeg'" />
                        <div class="message-content">
                            {{ message.content }}
                        </div>
                    </template>

                    <!-- 发送消息 -->
                    <template v-else-if="message.type === 'sent'">
                        <div class="message-content">
                            {{ message.content }}
                        </div>
                        <el-avatar :size="36"
                            src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                    </template>
                </div>
            </div>

            <!-- 输入区域 -->
            <div class="chat-input">
                <div class="input-tools">
                    <el-button link>
                        <el-icon><Paperclip/></el-icon>
                    </el-button>
                    <el-button link>
                        <el-icon><Picture/></el-icon>
                    </el-button>
                </div>
                <el-input v-model="msg.message" type="textarea" :rows="3" placeholder="请输入消息..." class="message-input"
                    @keydown.enter.exact.prevent="sendMessage" />
                <div class="input-actions">
                    <el-button type="primary" :disabled="!msg.message.trim()" @click="sendMessage" class="send-button" color="#ffc200">
                        发送
                    </el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang='ts'>
import { ref, nextTick, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Picture, Paperclip } from '@element-plus/icons-vue'
import type { Message } from '@/types'

// 联系人数据结构
interface Contact {
    id: number
    name: string
    avatar: string
    lastMessage?: string
}

const msg = ref<Message>({
    message: '',
    receiveUid: null
})

const messages = ref<Array<{ type: string, content: string, timestamp?: Date }>>([])

// 联系人列表
const contacts = ref<Contact[]>([
    {
        id: 1,
        name: '客服小助手',
        avatar: 'https://cube.elemecdn.com/3/7c/3ea455e5a2e2d3d0f7a5a1c7c5d3b.jpeg',
        lastMessage: '您好，有什么可以帮助您的吗？'
    },
])

// 选中的联系人
const selectedContact = ref<Contact | null>(null)

// 消息容器引用
const messagesContainer = ref<HTMLElement | null>(null)

let ws: WebSocket | null = null

// 选择联系人
const selectContact = (contact: Contact) => {
    selectedContact.value = contact
    // 清空当前消息
    messages.value = []
    // 初始化WebSocket连接或切换联系人
    initWebSocket(contact.id)
}

// 初始化WebSocket连接
const initWebSocket = (contactId: number) => {
    // 关闭之前的连接
    if (ws) {
        ws.close()
    }

    // 创建新的WebSocket连接
    ws = new WebSocket('ws://192.168.31.24:8080/websocket/' + contactId)

    ws.onopen = () => {
        ElMessage.success(`已连接到 ${selectedContact.value?.name}`)
    }

    ws.onmessage = (event) => {
        console.log('接收到消息：', event.data)
        messages.value.push({
            type: 'received',
            content: event.data,
            timestamp: new Date()
        })
        scrollToBottom()
    }

    ws.onerror = (error) => {
        ElMessage.error('连接出错，请稍后重试')
        console.error('WebSocket error:', error)
    }
}

onMounted(() => {
    // 默认选择第一个联系人
    if (contacts.value.length > 0) {
        selectContact(contacts.value[0])
    }
})

const sendMessage = () => {
    if (!msg.value.message.trim()) {
        ElMessage.warning('请输入消息内容')
        return
    }

    if (!ws || ws.readyState !== WebSocket.OPEN) {
        ElMessage.error('连接已断开，请重新选择联系人')
        return
    }

    ws.send(JSON.stringify(msg.value))

    // 将发送的消息添加到本地消息列表
    messages.value.push({
        type: 'sent',
        content: msg.value.message,
        timestamp: new Date()
    })

    console.log('发送消息:', msg.value)

    // 清空输入框
    msg.value.message = ''

    // 滚动到底部
    scrollToBottom()
}

// 滚动到底部
const scrollToBottom = () => {
    nextTick(() => {
        if (messagesContainer.value) {
            messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
        }
    })
}
</script>

<style lang='scss' scoped>
.message-page {
    display: flex;
    width: 100%;
    height: 100%;
    box-sizing: border-box;
}

.contacts-panel {
    width: 260px;
    border-right: 1px solid #f0f0f0;
    background: #fff;
    display: flex;
    flex-direction: column;

    .contacts-header {
        padding: 15px 20px;
        border-bottom: 1px solid #f0f0f0;

        h3 {
            margin: 0;
            font-size: 16px;
            font-weight: 500;
        }
    }

    .contacts-list {
        flex: 1;
        overflow-y: auto;

        .contact-item {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            cursor: pointer;
            border-bottom: 1px solid #f5f5f5;

            &:hover {
                background-color: rgba(255,194,0,0.3);
            }

            &.active {
                background-color: rgba(255,194,0,0.3);
            }

            .contact-info {
                margin-left: 12px;
                flex: 1;
                min-width: 0;

                .contact-name {
                    font-size: 14px;
                    font-weight: 500;
                    color: #333;
                    margin-bottom: 4px;
                }

                .contact-last-message {
                    font-size: 12px;
                    color: #999;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }
            }
        }
    }
}

.chat-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 100%;
    background: #fff;
    overflow: hidden;
}

.chat-messages {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    background: #f5f5f5;

    .message-date {
        text-align: center;
        margin-bottom: 20px;
        font-size: 12px;
        color: #999;
    }

    .message-item {
        display: flex;
        margin-bottom: 20px;

        &.system {
            justify-content: center;

            .message-content {
                background: #e6e6e6;
                color: #666;
                font-size: 12px;
                padding: 6px 12px;
                border-radius: 4px;
            }
        }

        &.received {
            .message-content {
                background: #fff;
                color: #333;
                border-radius: 0 12px 12px 12px;
                margin-left: 10px;
            }
        }

        &.sent {
            justify-content: flex-end;

            .message-content {
                background: #409eff;
                color: #fff;
                border-radius: 12px 0 12px 12px;
                margin-right: 10px;
            }
        }

        .message-content {
            max-width: 70%;
            padding: 12px 16px;
            line-height: 1.5;
            font-size: 14px;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
        }

        .el-avatar {
            flex-shrink: 0;
        }
    }
}

.chat-input {
    padding: 15px;
    background: #fff;
    border-top: 1px solid #f0f0f0;

    .input-tools {
        margin-bottom: 10px;

        .el-button {
            margin-right: 10px;
            color: #999;

            &:hover {
                color: #ffc200;
            }
        }
    }

    .message-input {
        margin-bottom: 10px;

        :deep(.el-textarea__inner) {
            resize: none;
            border-radius: 8px;
            border: 1px solid #dcdfe6;
            padding: 12px 16px;
            font-size: 14px;
            line-height: 1.5;

            &:focus {
                border-color: #409eff;
                outline: none;
                box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
            }

            &::placeholder {
                color: #c0c4cc;
            }
        }
    }

    .input-actions {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        gap: 10px;

        .send-button {
            padding: 10px 20px;
            font-size: 14px;
            transition: all 0.2s ease;

            &:disabled {
                color: #666;
                cursor: not-allowed;
            }
        }
    }
}
</style>